﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;

namespace Persistencia
{
    public  class TransaccionSesion : TransaccionBase
    {
        private SqlTransaction sTran { get; set; }

        private Sesion sesion;
        internal TransaccionSesion(string nombre,Sesion sesion)
            : base(nombre)
        {
            this.sesion = sesion;
        }

        public void Persistir()
        {
            try
            {
                sTran = base.Conexion.BeginTransaction();

                foreach (Factoria factoria in this.factorias.Values)
                    factoria.Persistir();

                sTran.Commit();
            }
            catch (Exception ex)
            {
                sTran.Rollback();
                sTran = null;
                throw ex;
            }

            this.RefrescarCache();
        }

        private void RefrescarCache()
        {
            foreach (Factoria factoria in factorias.Values)
                TransaccionCache.Transaccion.Refrescar(factoria);
        }

        public override void Cerrar()
        {
            sesion.CerrarTransaccion(this);
            base.Cerrar();
        }

        internal override SqlTransaction SQLTran
        {
            get { return sTran; }
        }
    }
}
